///
//  KKBLEAccept.m
//
//  Created by zorro on 2017/11/13.
//  Copyright © 2017年 zorro. All rights reserved.
//

#import "KKBLEAccept.h"
#import "KKBLEService.h"
#import "FileModelEntity.h"
#import "SportModeModel.h"

@interface KKBLEAccept (){
    KKBLEAcceptBlock block;
}

@end

@implementation KKBLEAccept
- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

// 高速通道
- (void)updateSpeedData:(NSData *)data updatePeripheral:(CBPeripheral *)peripheral
{
    UInt8 val[20] = {0};
    [data getBytes:&val length:data.length];
    NSString *content = [NSString stringWithFormat:@"%@", data];
    int result = val[7];
    BOOL err = intConvertBit(result, 5);
    BOOL ack = intConvertBit(result, 4);
    //    NSLog(@"高速通道接收到蓝牙数据>>>>>%@ err>%i ack>%i",content,err,ack);//0001 0000
    if (err == 0 && ack) {
        // 校验成功
        [[NSNotificationCenter defaultCenter] postNotificationName:@"acceptAck" object:@"1"];
    }
    else
    {
        // 校验失败
        [[NSNotificationCenter defaultCenter] postNotificationName:@"acceptAck" object:@"0"];
    }
}

- (void)updateData:(NSData *)data updatePeripheral:(CBPeripheral *)peripheral {
    UInt8 val[20] = {0};
    [data getBytes:&val length:data.length];
    NSString *content = [NSString stringWithFormat:@"%@", data];
    NSLog(@"接收蓝牙数据content:%@",content);
    id       object   = data;
    // 时间
    if (val[1] == 0x02) {
        if (val[2] == 0x01) {
            _acceptType = KKBLEAcceptTypeTime;
            LogWrite(nil, content, @"设置时间成功");
            NSLog(@"设置时间成功>>>>");
        }
    }
    // MAC地址
    if (val[1] == 0x01) {
        if (val[2] == 0x01) {
            NSString *mac = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", val[3], val[4], val[5], val[6], val[7], val[8]];
            LogWrite(nil, content, ([NSString stringWithFormat:@"获取设备mac地址成功:%@", mac]));
            NSLog(@"获取设备mac地址>>>>%@", mac);
            if (mac) {
                [KK_BLEModel.bleUUID setObjectValue:[mac uppercaseString]];
                [KK_BLELastDeviceMac setObjectValue:mac];
            }
            KK_BLEModel.bleMAC = [mac uppercaseString];
            [KK_BLEModel updateToDB];
            [SN_USER updateToDB];
            _acceptType = KKBLEAcceptTypeDevideMAC;
        }
    }
    
    // 高通传输模式
    if (val[1] == 0x02) {
        if (val[2] == 0x11) {
            object = [NSString stringWithFormat:@"%d",val[3]];
            _acceptType = BLTAcceptTypeDataHightSpeed;
            //            NSLog(@"高速传输设置>>>%d",val[3]);
            NSString *value = [NSString stringWithFormat:@"%d",val[3]];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"acceptSpeed" object:value];
        }
    }
    
    // 2019.05.15 屏保开关
    if (val[1] == 0x02) {
        if (val[2] == 0x12) {
            LogWrite(nil, content, @"获取屏保开关成功");
            KK_BLEModel.bleScreenImagesSwitchState = [NSString stringWithFormat:@"%d",val[3]];
            _acceptType = BLTAcceptTypeDataScreenImageSwitchState;
            [KK_BLEModel updateToDB];
            [SN_USER updateToDB];
        }
    }
    
    //2019.05.16 获取屏保图片信息
    if (val[1] == 0x01) {
        if (val[2] == 0x14) {
            LogWrite(nil, content, @"获取是否支持屏保图片成功");
            NSLog(@"获取是否支持屏保图片>>>>");
            // 0x00:保 留 0x01:支 持 0x02:不 支持
            KK_BLEModel.bleDeviceWidth          = val[3] + val[4];
            KK_BLEModel.bleDeviceHeight         = val[5] + val[6];
            KK_BLEModel.isSupportSetScreenImage = [NSString stringWithFormat:@"%d",val[7]];
            KK_BLEModel.bleScreenImagesSwitchState = [NSString stringWithFormat:@"%d",val[8]];
            KK_BLEModel.bleScreenTimeSwitchState = [NSString stringWithFormat:@"%d",val[9]];
            KK_BLEModel.bleScreenStepSwitchState = [NSString stringWithFormat:@"%d",val[10]];
            [KK_BLEModel updateToDB];
            [SN_USER updateToDB];
            _acceptType = BLTAcceptTypeDataScreenSaverInfo;
        }
    }
    
    // 2019.5.18
    // 获取设备支持屏保的字体种类及对应分辨率
    if (val[1] == 0x01) {
        if (val[2] == 0x15) {
//            NSMutableArray *array = [NSMutableArray array];
//            for (int i = 0; i < 4; i++) {
//                NSString *str = [NSString stringWithFormat:@"%02x%02x",val[4 + 2*i],val[4+ 2 *i + 1]];
//                [array addObject:str];
//            }
//            NSLog(@"content:%@,\n array:%@",content,array);
            LogWrite(nil, content, @"获取设备支持屏保的字体种类及对应分辨率成功");
            NSMutableArray *array1 = [NSMutableArray array];
            for (int i = 0; i < 8; i++) {
                char bytes[]={val[4 + 2*i],val[4+ 2 *i + 1]};
                unsigned char  by1 = (bytes[0] & 0xff); //高8位
                unsigned char  by2 = (bytes[1] & 0xff);//低8位
                int   temp  = (by2|(by1<<8));
                [array1 addObject:@(temp)];
            }
            NSLog(@"content:%@,\n array1:%@",content,array1);
            [[NSUserDefaults standardUserDefaults] setObject:array1 forKey:@"FontWidthHight"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            _acceptType = BLTAcceptTypeDataScreenSaverFontType;
        }
    }
    
    
    // 2019.5.17 APP 设置设备屏保显示时间的具体信息
    if (val[1] == 0x02) {
        if (val[2] == 0x13) {
            if (val[3] == 1) {
                _acceptType = BLTAcceptTypeDataScreenTimeLocation;
                NSLog(@"设置设备屏保显示时间的具体信息成功>>%d",val[3]);
                LogWrite(nil, content, @"设置设备屏保显示时间的具体信息成功");
            } else {
                NSLog(@"设置设备屏保显示时间的具体信息失败>>%d",val[3]);
                LogWrite(nil, content, @"设置设备屏保显示时间的具体信息失败");
            }
        }
    }
    
    // 2019.5.17 APP 设置设备屏保显示记步的具体信息
    if (val[1] == 0x02) {
        if (val[2] == 0x14) {
            if (val[3] == 1) {
                _acceptType = BLTAcceptTypeDataScreenStepLocation;
                NSLog(@"设置设备屏保显示记步的具体信息成功>>%d",val[3]);
                LogWrite(nil, content, @"设置设备屏保显示记步的具体信息成功");
            } else {
                NSLog(@"设置设备屏保显示记步的具体信息失败>>%d",val[3]);
                LogWrite(nil, content, @"设置设备屏保显示记步的具体信息失败");
            }
        }
    }
    
    // 2019.05.23
    // APP 设置设备实时运动数据的上传方式返回值
    if (val[1] == 0x02) {
        if (val[2] == 0x15) {
            if (val[3] == 1) {
                NSLog(@"设置设备实时运动数据的上传方式成功");
                LogWrite(nil, content, @"设置设备实时运动数据的上传方式成功");
            } else {
                NSLog(@"设置设备实时运动数据的上传方式失败");
                LogWrite(nil, content, @"设置设备实时运动数据的上传方式失败");
            }
        }
    }
    
    // 2019.06.04 运动模式
    if (val[1] == 0x07) {
        if (val[2] == 0x0B) {
//            NSLog(@"序号：0x%02x , 运动模式:0x%02x , 开始时间戳：0x%02x%02x%02x%02x, 持续时间:0x%02x%02x, 记步数:0x%02x%02x, 距离：0x%02x%02x, 卡路里:0x%02x%02x, max:0x%02x , min :0x%02x, 平均心率:0x%02x",val[3],val[4],val[5],val[6],val[7],val[8],val[9],val[10],val[11],val[12], val[13],val[14],val[15],val[16],val[17],val[18],val[19]);
            [SportModeModel updataSportModeData:data];
            
        }
        if (val[2] == 0xf9) {
            NSLog(@"运动模式获取完成");
            _acceptType = BLTAcceptTypeDataSportModeData;
        }
    }
    
    // 设备信息
    if (val[1] == 0x01) {
        if (val[2] == 0x02) {
            LogWrite(nil, content, @"获取设备信息成功");
            NSLog(@"获取设备信息>>>>");
            KK_BLEModel.deviceID        = val[3] * 256 + val[4];   // 设备ID;
            KK_BLEModel.bleVersion      = val[5];                  // 固件版本
            KK_BLEModel.batteryQuantity = val[7];                  // 电池电量
            int customerID = val[8] * 256 + val[9];
            if (customerID >0) {
                KK_BLEModel.bleCustomerID = customerID;
            }
            SN_USER.bleBatteryQuantity = val[7];
            if (KK_BLEModel.bleCustomerID == 1) {
                SN_USER.heartFunction        = intConvertBit(val[10], 0);
                SN_USER.bpFunction           = intConvertBit(val[10], 1);
                SN_USER.oxFunction           = intConvertBit(val[10], 2);
                // 2019.06.04 运动模式
                SN_USER.sportModeFunction    = intConvertBit(val[10], 3);
            } else {
                SN_USER.heartFunction        = NO;
                SN_USER.bpFunction           = NO;
                SN_USER.oxFunction           = NO;
                // 2019.06.04 运动模式
                SN_USER.sportModeFunction    = NO;
            }
            // 0000 1111
            NSInteger geshu = val[11]&0x0f;
            NSInteger full = (val[11]>>4)-1;
            
            if (full >0) {
                NSInteger current =  (NSInteger)(100.0*geshu/full);
                KK_BLEModel.batteryQuantity = current;
                NSLog(@"显示电量格式>>>%d",current);
                KK_BLEModel.fullPower = full;
                KK_BLEModel.currentPower = geshu;
            }
            
            NSLog(@"SN_USER.heartFunction>>>>%d bleCustomerID %d", SN_USER.heartFunction, KK_BLEModel.bleCustomerID);
            [KK_BLEModel updateToDB];
            [SN_USER updateToDB];
            [[FileModelEntity sharedInstance]checkUpdateFirmwareInfo];
            _acceptType = KKBLEAcceptTypeDevideInfo;
        }
    }
    
    if (val[1] == 0x02) {
        if (val[2] == 0x02) {
            _acceptType = KKBLEAcceptTypeUserInfo;
            LogWrite(nil, content, @"用户信息设置成功");
            NSLog(@"用户信息设置成功>>>");
        } else if (val[2] == 0x04) {
            _acceptType = KKBLEAcceptTypeAlarmClock;
            LogWrite(nil, content, @"闹钟设置成功");
        } else if (val[2] == 0x05) {
            _acceptType = KKBLEAcceptTypeCalendar;
            LogWrite(nil, content, @"日程设置成功");
        } else if (val[2] == 0x06) {
            _acceptType = KKBLEAcceptTypeDrink;
            LogWrite(nil, content, @"喝水提醒设置成功");
            NSLog(@"喝水提醒设置成功>>>");
        } else if (val[2] == 0x07) {
            _acceptType = KKBLEAcceptTypeSedentary;
            LogWrite(nil, content, @"久坐提醒设置成功");
            NSLog(@"久坐提醒设置成功>>>");
        } else if (val[2] == 0x09) {
            _acceptType = KKBLEAcceptTypeNotify;
            LogWrite(nil, content, @"消息推送设置成功");
            NSLog(@"消息推送设置成功>>>");
        } else if (val[2] == 0x0a) {
            if (val[3] == 0x01) {
                _acceptType = KKBLEAcceptTypeOther;
                LogWrite(nil, content, @"低电量以及其他设置");
                NSLog(@"低电量以及其他设置成功>>>");
            }
        } else if (val[2] == 0x0b) {
            if (val[3] == 0x01) {
                _acceptType = KKBLEAcceptTypeOther;
                LogWrite(nil, content, @"免打扰设置成功");
                NSLog(@"免打扰设置成功>>>");
            }
        }
           else if (val[2] == 0x0e)
           {    _acceptType = KKBLEAcceptTypeTemperature;
                LogWrite(nil, content, @"天气设置成功");
                NSLog(@"天气设置成功>>>");
           }
    }
    
    if (val [1] == 0x05) {
        if (val[2] == 0x03 && val[3] == 0x01) {
            //            _acceptType = KKBLEAcceptTypeFindBle;
            LogWrite(nil, content, @"寻找手环成功");
        }
    }
    
    //拍照
    if (val[1] == 0x06) {
        if (val[2] == 0x01) {
            [SN_PublicClass.BLTControlTDelegateTakePhoto bltControlTakePhoto];
            LogWrite(nil, content, @"接收手环拍照指令");
        }
        if (val[2] == 0x02) {
            [SN_PublicClass.BLTControlTDelegateFindPhone bleControlFindPhone];
            LogWrite(nil, content, @"接收手环找手机指令");
        }
    }
    
    // 实时步数
    if (val[1] == 0x07) {
        if (val[2] == 0x01) {
            if (data.length > 3) {
                LogWrite(nil, content, @"获取实时步数成功");
                _acceptType = KKBLEAcceptTypeRealtimeSport;
                [SN_PublicClass.todaySport updateRealStepData:data];
                // 本地通知
                NSInteger tmpStep     = val[3] * 256 * 256 * 256 + val[4] * 256 * 256 + val[5] * 256 + val[6];
                NSString *title = SN_Text(@"总步数");
                NSString *subtitle = [NSString stringWithFormat:@"%ld%@",(long)tmpStep,SN_Text(@"步")];
                NSString *identifier = @"latestRealSportData";
//                [kK_App latestRealSportDataNotification:title subtitle:subtitle identifier:identifier];
            }
        }
    }
    
    // 大数据 1 运动
    if (val[1] == 0x07) {
        if (val[2] == 0x03) {
            //记步大数据
            [SportModel updateSportData:data];
        } else if (val[2] == 0x05) {
            //距离大数据
            [SportModel updateSportData:data];
        } else if (val[2] == 0x06) {
            //卡路里大数据
            [SportModel updateSportData:data];
        } else if (val[2] == 0xFF) {
            [SportModel sportTransEnd];
            // 运动结束
            _acceptType = KKBLEAcceptTypeDataSport;
        }
    }
    
    if (val[1] == 0x07) {
        if (val[2] == 0x04) {
            [SleepModel updateSleepData:data];
        } else if (val[2] == 0xFE) {
            // 睡眠结束
            [SleepModel sleepTransEnd];
            _acceptType = KKBLEAcceptTypeDataSleep;
        }
    }
    
    if (val[1] == 0x07) {
        if (val[2] == 0x07) {
            [HeartModel updateHeartData:data];
        } else if (val[2] == 0xFD) {
            // 心率
            [HeartModel heartTransEnd];
            _acceptType = KKBLEAcceptTypeDataHeart;
        }
    }
    if (val[1] == 0x07) {
        if (val[2] == 0x02) {
            if (SN_PublicClass.checkType == 1 && val[3] > 0) {
                [SN_PublicClass.todayHeart updateRealHeartData:val[3]];
                _acceptType = KKBLEAcceptTypeRealtimeHeart;
            }
            if (SN_PublicClass.checkType == 2 && val[4] > 0) {
                [SN_PublicClass.todayOx updateRealOXData:val[4]];
                _acceptType = KKBLEAcceptTypeRealtimeOX;
            }
            if (SN_PublicClass.checkType == 3 && val[5] > 0 && val[6] > 0) {
                if (SN_PublicClass.bpValue.length == 0) {
                    [SN_PublicClass.todayBp updateRealBPData:val[5] withBp:val[6]];
                    SN_PublicClass.bpValue = [NSString stringWithFormat:@"%@_%@",StrByInt(val[5]),StrByInt(val[6])];
                  NSLog(@"收到血压>>>%@",[NSString stringWithFormat:@"%@_%@",StrByInt(val[5]),StrByInt(val[6])]);
                 _acceptType = KKBLEAcceptTypeRealtimeBP;
                }
            }
        }
    }
    
//    if (block) {
//        block(object, _acceptType);
//    }
    
    if (_acceptStatus) {
        _acceptStatus(object, _acceptType);
    }
    if (KK_BLEConnect.bleConnectAcceptBlock) {
        KK_BLEConnect.bleConnectAcceptBlock(object, _acceptType);
    }
}

@end

